<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select
        v-model="listQuery.channelId"
        filterable
        clearable
        :filter-method="dataFilter"
        placeholder="选择渠道"
        style="width: 150px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option
          v-for="item in options"
          :key="item.channelId"
          :label="item.channel_name"
          :value="item.channelId"
        />
      </el-select>
      <el-select
        v-model="listQuery.type"
        clearable
        placeholder="选择协议类型"
        style="width: 150px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      >
        <el-option :value="21" label="个人信息共享协议书"
          >个人信息共享协议书</el-option
        >
        <el-option :value="22" label="助贷服务协议">助贷服务协议</el-option>
        <el-option :value="23" label="个人信息授权书">个人信息授权书</el-option>
        <el-option :value="24" label="用户注册协议">用户注册协议</el-option>
        <el-option :value="25" label="用户隐私协议">用户隐私协议</el-option>
      </el-select>
      <el-input
        v-model="listQuery.name"
        placeholder="用户名"
        style="width: 100px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        v-waves
        class="filter-item"
        type="success"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增
      </el-button>
    </div>
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="tableData"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="协议名称" class-name="status-col" min-width="110">
        <template slot-scope="{ row }">
          {{ row.name }}
        </template>
      </el-table-column>
      <!-- <el-table-column label="协议类型" width="150" align="center">
        <template slot-scope="{ row }">
          <span>{{ channelIdText[row.type] }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="渠道" width="150" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.channelName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" width="150">
        <template slot-scope="{ row }">
          <span>{{
            `${row.gmtDatetime[0]}-${row.gmtDatetime[1]}-${
              row.gmtDatetime[2]
            } ${row.gmtDatetime[3]}:${row.gmtDatetime[4]}`
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="协议内容" width="80" align="center">
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="handleView(row)">
            查看
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="110"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button size="mini" type="primary" @click="handleEdit(row)">
            编辑
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getProtocolList"
    />
    <!-- <el-dialog :visible="viewProtocolialog"> </el-dialog>> -->
    <el-dialog
      width="50%"
      title="协议内容"
      :visible.sync="viewProtocolialog"
      append-to-body
    >
      <div v-html="htmlContent" />
    </el-dialog>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="channelReqDto"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-input v-model="channelReqDto.id" type="hidden" />
        <el-form-item label="协议名称" prop="name">
          <el-input v-model="channelReqDto.name" />
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
          <el-select
            v-model="channelReqDto.channelId"
            filterable
            :filter-method="dataFilter"
            placeholder="选择渠道"
            style="width: 300px;"
            class="filter-item"
          >
            <el-option
              v-for="item in options"
              :key="item.channelId"
              :label="item.channel_name"
              :value="item.channelId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select
            v-model="channelReqDto.type"
            clearable
            placeholder="请选择类型"
            style="width: 300px;"
            class="filter-item"
          >
            <el-option :value="21" label="个人信息共享协议"
              >个人信息共享协议</el-option
            >
            <el-option :value="22" label="助贷服务协议">助贷服务协议</el-option>
            <el-option :value="23" label="个人信息授权书"
              >个人信息授权书</el-option
            >
            <el-option :value="24" label="用户注册协议">用户注册协议</el-option>
            <el-option :value="25" label="用户隐私协议">用户隐私协议</el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="协议内容" prop="htmlContent">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="channelReqDto.htmlContent"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch
            active-color="#13ce66"
            inactive-color="#ff4949"
            v-model="channelReqDto.state"
            @change="changeSwitch($event, scoped.row, scoped.$index)"
          >
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog title="协议修改" :visible.sync="channelConfdialog">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="channelConf"
        label-position="left"
        label-width="90px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="渠道ID" label-width="120px">
          <el-input v-model="channelConf.channelId" readonly="readonly" />
        </el-form-item>
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="channelConf.userName" />
        </el-form-item>
        <el-form-item label="Token" label-width="120px">
          <el-input v-model="channelConf.token" />
        </el-form-item>
        <el-form-item label="登录注册" label-width="120px">
          <el-radio-group v-model="channelConf.needAuthLogin" size="small">
            <el-radio :label="1">
              开启
            </el-radio>
            <el-radio :label="0">
              关闭
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item
          label="跳转停留毫秒数"
          v-if="radioState == 1"
          label-width="120px"
        >
          <el-input type="number" v-model="channelConf.milliSeconds" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="channelConfdialog = false">
          取消
        </el-button>
        <el-button type="primary" @click="updateChannelSetting()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
const column = ['渠道ID', '名称', '用户名', '协议内容', '渠道签名', '操作'];
import { getChannelIdAndNick } from '@/api/user';
import {
  getProtocolList,
  saveProtocol,
  editProtocol,
  viewProtocol
} from '@/api/sys.js';
import { updateChannelSetting } from '@/api/channel';
import waves from '@/directive/waves'; // waves directive
import Pagination from '@/components/Pagination'; // secondary package based on el-pagination

export default {
  name: 'Channellist',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      isIndeterminate: true,
      checkList: ['渠道ID', '名称', '协议', '操作'],
      channelIdText: {
        // 20: '吉客授权书',
        21: '个人信息共享协议书',
        22: '助贷服务协议',
        23: '个人信息授权书',
        24: '用户注册协议',
        25: '用户隐私协议'
      },
      columnName: column,
      tableData: [],
      total: 0,
      tableKey: 0,
      listQuery: {
        current: 1,
        size: 10,
        channelId: '',
        name: '',
        type: ''
      },
      channelReqDto: {
        channelId: undefined,
        name: '',
        type: '',
        htmlContent: '',
        state: true
      },
      channelConf: {
        id: undefined,
        channelId: '',
        kouliang: '',
        payMethod: '',
        vipprice: '',
        token: ''
      },
      dialogFormVisible: false,
      channelConfdialog: false,
      viewProtocolialog: false,
      channelauthConfdialog: false,
      htmlContent: '',
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '新增'
      },
      rules: {
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        name: [{ required: true, message: '请选择类型', trigger: 'change' }],
        htmlContent: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        channelId: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        timestamp: [
          {
            type: 'date',
            required: true,
            message: 'timestamp is required',
            trigger: 'change'
          }
        ],
        nickname: [{ required: true, message: '名称必填', trigger: 'blur' }]
      },
      optionsCopy: [],
      options: [],
      listLoading: false,
      radioState: null
    };
  },
  created() {
    this.getProtocolList(this.listQuery);
    this.getChannelIdAndNick();
    console.log(this.channelIdText[21]);
  },
  watch: {
    'channelConf.jumpPage'(newVal, oldVal) {
      this.radioState = newVal;
    },
    'dynamicValidateForm.domains': {
      handler(newArr) {
        // 一开始都设置为允许使用
        this.h5Arr = this.h5Arr.map(item => {
          item.disabled = false;
          return item;
        });
        // 将选过的设置为禁用
        newArr.forEach(x => {
          this.h5Arr.forEach(y => {
            if (x.value === y.value) {
              y.disabled = true;
            }
          });
        });
      },
      deep: true
    }
  },
  methods: {
    dataFilter(val) {
      this.value = val;
      if (val) {
        // val存在
        this.options = this.optionsCopy.filter(item => {
          if (
            !!~item.channel_name.indexOf(val) ||
            !!~item.channel_name.toUpperCase().indexOf(val.toUpperCase())
          ) {
            return true;
          }
        });
      } else {
        // val为空时，还原数组
        this.options = this.optionsCopy;
      }
    },
    async getProtocolList(listQuery) {
      const res = await getProtocolList(this.listQuery);
      if (res.data.code === 200) {
        this.tableData = res.data.data.records;
        this.total = res.data.data.total;
      }
    },
    async getChannelIdAndNick() {
      const res = await getChannelIdAndNick(this.listQuery);
      res.data.data.forEach(element => {
        if (element.channel_name !== null) {
          this.optionsCopy.push(element);
          this.options.push(element);
        }
      });
    },
    async handleView(row) {
      this.htmlContent = '';
      this.viewProtocolialog = true;
      const res = await viewProtocol({ uid: row.uid });
      this.htmlContent = res.data.data.htmlContent;
    },

    // 搜索
    handleFilter() {
      this.listQuery.current = 1;
      if (!this.listQuery.channelId) {
        this.getProtocolList(this.listQuery);
      } else {
        this.options.forEach(element => {
          if (element.channelId === this.listQuery.channelId) {
            this.listQuery.nickname = element.channel_name;
            this.getProtocolList(this.listQuery);
          }
        });
      }
    },
    resetTemp() {
      this.channelReqDto = {
        channelId: undefined,
        name: '',
        type: '',
        htmlContent: '',
        state: true
      };
    },
    updateChannelSetting() {
      updateChannelSetting(this.channelConf).then(res => {
        if (res.data.code === 200) {
          this.$notify({
            title: '更新配置',
            message: '更新成功！',
            type: 'success',
            duration: 2000
          });
        } else {
          this.$notify({
            title: '更新配置',
            message: '更新失败！',
            type: 'fail',
            duration: 2000
          });
        }
        this.channelConfdialog = false;
      });
    },
    // 编辑协议
    async handleEdit(row, statetype) {
      this.dialogStatus = 'edit';
      this.dialogFormVisible = true;
      const res = await viewProtocol({ uid: row.uid });
      this.channelReqDto = res.data.data;
      this.channelReqDto.state = this.channelReqDto.state === 1 ? true : false;
    },
    // 新增协议
    handleCreate() {
      this.resetTemp();
      this.dialogStatus = 'create';
      this.dialogFormVisible = true;
      //   createSign({ data: new Date() }).then(res => {
      //     this.channelReqDto.channelSign = res.data.data;
      //     if (res.data.code === 200) {

      //     } else {
      //       this.$notify({
      //         title: '错误',
      //         message: '失败',
      //         type: 'fail',
      //         duration: 2000
      //       });
      //     }
      //   });
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate();
      });
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.channelReqDto.state = this.channelReqDto.state === true ? 1 : 0;
          const base64 = new Buffer(this.channelReqDto.htmlContent).toString(
            'base64'
          );
          this.channelReqDto.htmlContent = base64;
          saveProtocol(this.channelReqDto).then(res => {
            if (res.data.code === 200) {
              this.dialogFormVisible = false;
              this.$notify({
                title: 'Success',
                message: 'create Successfully',
                type: 'success',
                duration: 2000
              });
            } else {
              this.$notify({
                title: '错误',
                message: res.data.msg,
                type: 'fail',
                duration: 2000
              });
            }
            this.getProtocolList();
          });
        }
      });
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.channelReqDto.state = this.channelReqDto.state === true ? 1 : 0;
          const base64 = new Buffer(this.channelReqDto.htmlContent).toString(
            'base64'
          );
          this.channelReqDto.htmlContent = base64;
          console.log(this.channelReqDto, '----');
          editProtocol(this.channelReqDto).then(res => {
            if (res.data.code === 200) {
              this.dialogFormVisible = false;
              this.$notify({
                title: 'Success',
                message: 'edit Successfully',
                type: 'success',
                duration: 2000
              });
            } else {
              this.$notify({
                title: '错误',
                message: res.data.msg,
                type: 'fail',
                duration: 2000
              });
            }
            this.getProtocolList();
          });
        }
      });
    }
  }
};
</script>
<style scoped>
.pic {
  width: 150px;
  margin-top: 10px;
  margin-left: 10px;
}
.ok {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(35, 248, 124);
}
.fail {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
  color: rgb(240, 174, 76);
}
.info {
  margin-left: 10px;
  margin-top: 10px;
  font-weight: 5 00;
}
.info-name {
  margin-left: 50px;
  margin-top: 10px;
  color: rgb(172, 176, 177);
}
.title {
  margin-top: 10px;
  margin-left: 10px;
  font-size: 20px;
  font-weight: 400;
}
.box {
  margin-top: 10px;
  width: 100%;
  border: solid rgb(138, 219, 230) 2px;
}
.nick {
  font-size: 30px;
  font-weight: 600;
}
.link-top {
  margin-left: 10px;
  margin-top: 10px;
  width: 100%;
  height: 2px;
  border-top: solid rgb(138, 219, 230) 2px;
}
.link-title {
  margin-left: 10px;
  margin-top: 10px;
  width: 80px;
  height: 2px;
  border-top: solid rgb(172, 176, 177) 2px;
}
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>
